package zzxkj.blog.cacheService;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import zzxkj.blog.utils.RedisUtil;

import java.util.*;

/**
 * @author zzxkj
 */
@Slf4j
@Component
public class RankListService {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取周排行榜
     * 注意：最近7天内发布的文章，才会参与排行
    * */
    public List<Map> getWeekRank(){
        String key = "rank:week";
        Set<ZSetOperations.TypedTuple> tuples = redisUtil.getZSetRank(key,0,6);
        List<Map> result = new ArrayList<>();
        for (ZSetOperations.TypedTuple typedTuple : tuples){
            Map<String,Object> map = new HashMap<>();
            //文章的id
            Object value = typedTuple.getValue();
            //redis中hash类型缓存的文章的key
            String postKey = "rank:blog:" + value;
            map.put("id", value);
            map.put("title", redisUtil.hget(postKey,"title"));
            map.put("views", redisUtil.hget(postKey,"views"));
            result.add(map);
        }
        return result;
    }
    public List<Map> getAllRank(){
        String key = "rank:all";
        Set<ZSetOperations.TypedTuple> tuples = redisUtil.getZSetRank(key,0,6);
        List<Map> result = new ArrayList<>();
        for(ZSetOperations.TypedTuple typedTuple : tuples){
            Object value = typedTuple.getValue();
            Double score = typedTuple.getScore();
            JSONObject json = JSONUtil.parseObj(value);
            Map<String, Object> map = new HashMap<>();
            map.put("id", json.getStr("id"));
            map.put("title", json.getStr("title"));
            map.put("views", score.intValue());
            result.add(map);
        }
        return result;
    }
}
